package com.atom.module.mvvm.extren

import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.annotation.CheckResult
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate

@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
fun OnBackPressedDispatcher.backPresses(owner: LifecycleOwner) = callbackFlow<Unit> {
        checkMainThread()
        val callback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                trySend(Unit)
            }
        }
        addCallback(owner, callback)
        awaitClose { callback.remove() }
    }.conflate()